package com.bjpowernode.util;

import java.io.IOException;
import java.net.HttpURLConnection;

import java.net.URL;

/**
  http相关工具类,和下载目标服务器建立连接
 */
public class HttpUtils {

    /**
     * 获取下载文件大小
     * @param url
     * @return
     */
    public static Long getContentLength(String url){

        int contentLength;
        //获取链接
        HttpURLConnection httpURLConnection = null;
        try {
            httpURLConnection = getHttpURLConnection(url);
            contentLength = httpURLConnection.getContentLength();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(httpURLConnection != null){
                httpURLConnection.disconnect();
            }
        }
        return (long) contentLength;
    }

    /**
     * 分块下载
     * @param url      下载地址
     * @param startPos 下载文件起始地址
     * @param endPos   下载文件的结束地址
     * @return
     */
    public static HttpURLConnection getHttpURLConnection(String url, Long startPos , Long endPos) throws IOException {
        //通调用重载方法来获取链接对象
        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        LogUtils.info("下载的区间是：{}-{}", startPos, endPos);

        if(endPos != 0){
            //中间的区域块
            //bytes=100-1024
            httpURLConnection.setRequestProperty("RANGE", "bytes=" + startPos + "-" + endPos);
        }else{
            //最后一个区域块
            httpURLConnection.setRequestProperty("RANGE", "bytes=" + startPos + "-");
        }

        return httpURLConnection;
    }

    /**
     * 传递url获取http连接
     * @param url 文件地址
     * @return
     */
    public static HttpURLConnection getHttpURLConnection(String url) throws IOException {
        try {
            URL httpUrl = new URL(url);
            //获取连接
            HttpURLConnection httpURLConnection = (HttpURLConnection)httpUrl.openConnection();
            //向文件所在文件服务器发送标识信息
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36");
            return httpURLConnection;
        } catch (IOException e) {
            System.out.println("下载地址存在问题,出现了" + e + "异常");
            throw e;
        }
    }

    /**
     * 截取文件名和后缀exe程序名后缀
     * @param url
     * @return
     */
    public  static String getFileName(String url){
        return url.substring(url.lastIndexOf("/") + 1);
    }
}
